<template>
    <div id="login-phone" class="align-center">
        <div>
            <el-form :model="userMessage" ref="userMessageForm" :rules="rules">
                <el-form-item prop="phoneNum" :class="isError?'error':'right'">
                    <el-input v-model.trim="userMessage.phoneNum" @focus="focus" placeholder="输入手机号"></el-input>
                </el-form-item>
                <el-form-item prop="pwd" style="margin-bottom:0">
                    <el-input v-model="userMessage.pwd" placeholder="输入密码" type="password" show-password
                        @keyup.native.enter="login"></el-input>
                </el-form-item>
            </el-form>
            <div class="tips text-right" style="font-size:1.04vw;margin-top:0.833vw" @click="forgetPwd">忘记密码？</div>
            <button :class="['dis-button' ,{'use-btn':disbtn} ,'login-btn','pointer']" id="login-btn"
                :disabled="!disbtn" type="button" @click.prevent="login">登录</button>
        </div>
        <div>
            <div></div>
        </div>
    </div>
</template>

<script>
import user from '@/content/api/user'
import { SqlLib } from "../../../../../static/lib/sqlite/SqlLib";
import { User } from "../../../../../static/lib/sqlite/model/User";
import moment from 'moment'
import { SqlLibUser } from "../../../../../static/lib/sqlite/service/SqlLibUser";
const cryUtil = require('../../../../../static/utils/CrypUtil');

export default {
    inject: ["checkLoginPage"],
    data () {
        let phoeNum = (rule, value, callback) => {
            let rex = new RegExp(/^1\d{10}$/g)
            if (rex.test(value)) {
                this.isError = false
                return callback()
            } else {
                this.isError = true
                return callback(new Error('手机号输入错误'))
            }
        }
        return {
            userMessage: {
                phoneNum: "",
                pwd: ""
            },
            rules: {
                phoneNum: [{ validator: phoeNum, trigger: 'submit' }]
            },
            isError: false,
            isclick: false,
            keyEnter: false
        };
    },
    computed: {
        disbtn () {
            return !!(this.userMessage.phoneNum && this.userMessage.pwd)
        }
    },
    mounted () {
        let _this = this;
        this.$nextTick(() => {
            let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
            if (user && user.mobile) {
                _this.userMessage.phoneNum = user.mobile;
            }
        });
    },
    methods: {
        login () {
            if (!this.disbtn) return
            if (!this.checkLoginPage()) return
            if (this.keyEnter) return
            let _this = this;
            this.$refs.userMessageForm.validate(valid => {
                if (valid) {
                    _this.goLogin(_this.userMessage.phoneNum, _this.userMessage.pwd)
                } else {
                    this.isclick = true
                }
            })
        },
        goLogin (account, password, isRegister) {
            console.log("goLogin --> " + isRegister);
            let _this = this;
            _this.keyEnter = true;
            let version = _this.$readIniFile("data", "versionInfo");
            const params = {
                type: 0,
                loginAccount: account,
                password: password,
                currentVersion: version
            }
            _this.$showLoading("正在登录...");
            user.login(params).then(response => {
                _this.$closeLoading();
                if (response.code === "0") {
                    if (response.returnValue.isOverLimit && response.returnValue.isOverLimit == 1) {
                        _this.$dialog({
                            title: "提示",
                            confirm: '确定',
                            type: 'success',
                            message: '您的账号正在重复登录，其他登录地点即将下线',
                        }).then(value => {
                            if (value) {//确定按钮
                                localStorage.setItem('accesstoken', response.returnValue.accessToken)
                                localStorage.setItem('refreshToken', response.returnValue.refreshToken)
                                _this.getUserInfo(false, isRegister);
                            } else {
                                _this.keyEnter = false;
                            }
                        }).catch(err => {
                            console.log(err);
                            _this.keyEnter = false;
                        });
                    } else {
                        localStorage.setItem('accesstoken', response.returnValue.accessToken)
                        localStorage.setItem('refreshToken', response.returnValue.refreshToken);
                        _this.getUserInfo(false, isRegister);
                    }
                } else {
                    _this.keyEnter = false;
                    _this.$message.error(response.message);
                }
            }).catch(error => {
                _this.$closeLoading();
                _this.$message.error('网络异常！');
                _this.keyEnter = false;
            });
        },
        //获取用户信息
        getUserInfo (isAuto, isRegister) {
            let _this = this;
            let offlineUseTime = this.$readIniFile("data", "ofuTime");
            user.getUserInfo().then(response => {
                let resUser = response.returnValue;
                let user = new User();
                user.id = resUser.userBaseVO.userId;
                user.name = resUser.userBaseVO.fullName ? resUser.userBaseVO.fullName : "";
                user.mobile = resUser.userBaseVO.mobile ? resUser.userBaseVO.mobile : "";
                user.password = isAuto ? '' : cryUtil.aesEncrypt(_this.userMessage.pwd + "", user.id + "", true);
                user.avatar = resUser.userBaseVO.avatar ? resUser.userBaseVO.avatar : "";
                user.limitCount = resUser.userBaseVO.limitCount ? resUser.userBaseVO.limitCount : 1;
                user.schoolName = resUser.schoolName ? resUser.schoolName : "";
                user.schoolId = resUser.schoolId ? resUser.schoolId : "";
                user.isGlobal = resUser.isGlobal ? resUser.isGlobal : ''
                user.eduLevelId = resUser.eduLevelId ? resUser.eduLevelId : "";
                user.vipType = cryUtil.aesEncrypt(resUser.isVip + "", user.id + "", true);
                user.remainderDays = cryUtil.aesEncrypt(resUser.days + "", user.id + "", true);
                user.activeTime = moment().format('YYYY-MM-DD HH:mm:ss');
                user.bookId = resUser.bookId ? resUser.bookId : "";
                user.offlineExpired = offlineUseTime ? offlineUseTime : _this.$CONST.global.offlineDefaultDays;
                user.offlineExpired = cryUtil.aesEncrypt(user.offlineExpired + "", user.id + "", true);

                //更新用户信息
                let sqlInstance = SqlLib.getInstance(window.$DBDIR);
                let result = sqlInstance.updateOrInsertObjectById(user);
                if (sqlInstance.checkSqlError(result)) {
                    //需要重新检测网络
                    window.netStatus = false;
                    if (isRegister) {//如果是注册的登录，带上注册参数
                        _this.$router.push({ name: 'home', query: { isRegister: 1 } });
                        console.log("是注册的登录，带上注册参数");
                    } else {
                        _this.$router.push({ name: 'home' });
                        console.log("不是注册的登录");
                    }
                } else {
                    _this.$message("保存用户信息失败！")
                }
            }).catch(error => {
                console.log(error);
                _this.$message.error("获取用户信息失败！")
            })
        },
        //清除表单验证
        focus () {
            console.log(this.isclick)
            if (!this.isclick) return
            console.log(111)
            this.isError = false
            this.$refs.userMessageForm.clearValidate()
        },
        //找回密码
        forgetPwd () {
            this.$emit("changeRegister");
        }
    }
};
</script>

<style lang="scss">
#login-phone {
    .login-btn {
        width: 25vw;
        height: 3.33vw;
        margin-top: 1.667vw;
    }
}
</style>
